//
//  GZupdataViewController.m
//  运营管理系统
//
//  Created by 杨毅 on 16/9/22.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "GZupdataViewController.h"
#import "CustomPopOverView.h"
#import "IQKeyboardManager.h"
#import "IQKeyboardReturnKeyHandler.h"
#import "AppDelegate.h"
#import "AFNetworking.h"
#import "YXKit.h"
#import "Masonry.h"
#import "KKUploadPhotoCollectionViewCell.h"
#import "KKPhotoPickerManager.h"
#import "MBProgressHUD.h"
#import "ZJSwitch.h"
#import "GZchuliVC.h"
#import "MHActionSheet.h"
#import "TypeDataModel.h"
#import "SectionOneFaultModel.h"
#import "SectionTowFaultModel.h"
#import "SectionThreeFaultModel.h"
#import "ChooseMenus.h"
#import "Besicmodel.h"
#import "PHATextView.h"
#import "XJEqDataModel.h"//设备模型
static NSString *collectionViewCellId = @"collectionViewCellId";
static CGFloat imageSize = 80;

@interface GZupdataViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,CustomPopOverViewDelegate,ChooseMenusDataSource,UITextViewDelegate>
{
    UIView *_backview1;
    UIView *_backView2;
    UIView *_backView3;
    NSMutableArray *_stationName;//站点
    NSMutableArray *_sbName;//设备名称
    NSMutableArray *_GZtype;//故障类型
    NSMutableArray *_UpPsonNameArr;//上级人员
    NSMutableArray *_UpPsonId;

    NSInteger tag;
    IQKeyboardReturnKeyHandler *returnKeyHandler;
    NSString *_dateString;//当前时间
    NSMutableArray *_sbID;//设备id数组
    NSMutableArray *_typeID;//类型id数组

    NSInteger indexP;
    
    //提交传入参数
    NSInteger equipID;//设备id
    NSInteger fttpid;//类型id

    
    
    UIButton *_stationBtn;//站点选择btn

    UIButton *_sbBtn;//设备选择btn

    UIButton *_gztypeBtn;//故障类型选择btn

    UITextField *_gzTitleTF;//故障标题
    PHATextView *_detailText;//故障详情
    NSInteger switState;//swit状态  默认1
    UIButton *_updata;

    BOOL isSelect;
    ChooseMenus *_MenusView;
    
    NSMutableArray *_nameArr;
    NSMutableArray *_stationIdArray;
    NSMutableArray *_SBnameArr;
    NSMutableArray *_sbIDarr;
    NSDictionary *_paramete;//上报参数
    
    UILabel *_chosupPsonLab;
    NSInteger UpPsonId;
}

@property (nonatomic,strong)AFHTTPSessionManager *manager;
@property (nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic, strong) UICollectionView *collectionView; //添加图片,每个cell内有一个imageView
@property(nonatomic, strong) NSMutableArray *imageArray;
@property(nonatomic, strong) UILabel *stationTF;
@property(nonatomic, strong) UITextField *sbTF;
@property(nonatomic, strong) UITextField *gztypeTF;
@property (nonatomic,strong)NSMutableArray *dataSource0;
@property (nonatomic,strong)NSMutableArray *dataSource1;
@property (nonatomic,strong)NSMutableArray *dataSource2;
@property (nonatomic,strong)NSMutableArray *dataSource3;
@property (nonatomic,strong)NSMutableArray *typeIDArr1;
@property (nonatomic,strong)NSMutableArray *typeIDArr2;
@property (nonatomic,strong)NSMutableArray *typeIDArr3;

@property (nonatomic,strong)UIView *backView8;
@property (nonatomic,strong)UIView *backview7;

@property (nonatomic,strong)UIButton *chosUpPsonBtn;
@end

@implementation GZupdataViewController

- (AFHTTPSessionManager *)manager{
    
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self SBnetworking];
    [self shangjiPsonLoad];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"故障提交";
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    _stationName = [[NSMutableArray alloc]init];
    _sbName = [[NSMutableArray alloc]init];
    _sbID = [[NSMutableArray alloc]init];
    _UpPsonNameArr = [[NSMutableArray alloc]init];
    _UpPsonId = [[NSMutableArray alloc]init];
    switState = 1;
/*
    //读取保存在中间对象中的数据
    UIApplication *app = [UIApplication sharedApplication];
    
    AppDelegate *delegate = app.delegate;
    
    //获取注册界面保存的数据
    self.funcName = delegate.username;
    self.userId = delegate.userId;
*/
    NSString *doucumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //2.拼接上文件路径
    NSString *filtPath = [doucumentsPath stringByAppendingPathComponent:@"Log.txt"];
    //3.字典从文件中读取数据
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filtPath];
    if (dic != nil) {
        
        if (![[dic objectForKey:@"username"] isKindOfClass:[NSNull class]] && ![[dic objectForKey:@"password"] isKindOfClass:[NSNull class]]) {
            self.userId = [[dic objectForKey:@"userid"]integerValue];
            self.funcName = [dic objectForKey:@"username"];
            self.leve = [[dic objectForKey:@"level"]integerValue];
        }else{
            //读取保存在中间对象中的数据
            UIApplication *app = [UIApplication sharedApplication];
            
            AppDelegate *delegate = app.delegate;
            self.userId = delegate.userId;
            self.funcName = delegate.username;
            self.leve = delegate.level;
        }
    }
    self.imageArray = [NSMutableArray array];

    _dataSource0 = [[NSMutableArray alloc]init];
    _dataSource1 = [[NSMutableArray alloc]init];
    _dataSource2 = [[NSMutableArray alloc]init];
    _dataSource3 = [[NSMutableArray alloc]init];
    _typeIDArr1  = [[NSMutableArray alloc]init];
    _typeIDArr2  = [[NSMutableArray alloc]init];
    _typeIDArr3  = [[NSMutableArray alloc]init];

   
    _nameArr = [[NSMutableArray alloc]init];
    _stationIdArray = [[NSMutableArray alloc]init];
    _SBnameArr = [[NSMutableArray alloc]init];
    _sbIDarr = [[NSMutableArray alloc]init];

    
    [self initSroll];
    //解决键盘弹起挡住textview的方法
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].enable=YES;
}
- (void)initView{

    _MenusView = [[ChooseMenus alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height/3*2, self.view.frame.size.width, self.view.frame.size.height/3)];
    _MenusView.backgroundColor = [UIColor whiteColor];
    _MenusView.dataSource = self;
    //_MenusView.alpha = 0;
    [_MenusView typeIDOne:_typeIDArr1];
    [_MenusView typeIDTow:_typeIDArr2];
    [_MenusView typeIDThree:_typeIDArr3];
    [self.view addSubview:_MenusView];
    
    [_MenusView TitleBlock:^(NSString *block , NSInteger ID) {
        [_gztypeBtn setTitle:block forState:UIControlStateNormal];
        [_gztypeBtn setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
        fttpid = ID;

    }];

}

- (void)initSroll{
    
    [self.view addSubview:self.scrollView];
    //故障站点
    _backview1 = [[UIView alloc]initWithFrame:CGRectMake(0, 15, kSCREEN_WIDTH, 40)];
    _backview1.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_backview1];
    UIImageView *leftImage1 = [[UIImageView alloc]initWithFrame:CGRectMake(10, 7, 18, 25)];
    leftImage1.image = [UIImage imageNamed:@"f_icon03"];
    [_backview1 addSubview:leftImage1];
    UILabel *title1 = [[UILabel alloc]init];
    title1.text = @"故障站点:";
    title1.textColor = UIColorFromRGB(0x4d4d4d);
    title1.font = [UIFont systemFontOfSize:19.0];
    [_backview1 addSubview:title1];
    [title1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftImage1.mas_right).offset(16);
        make.top.equalTo(_backview1).offset(10);
        make.size.mas_equalTo(CGSizeMake(90, 21));
    }];

    self.stationTF = [[UILabel alloc]init];

    self.stationTF.text = self.stationN;
    self.stationTF.textColor = UIColorFromRGB(0x4d4d4d);
    self.stationTF.font = [UIFont systemFontOfSize:15.0];
    self.stationTF.backgroundColor = UIColorFromRGB(0xf0f0f0);
    self.stationTF.lineBreakMode = NSLineBreakByTruncatingMiddle;
    [_backview1 addSubview:self.stationTF];

    [self.stationTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_backview1).offset(5);
        make.left.equalTo(title1.mas_right).offset(5);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH-145, 30));
    }];
    //故障设备
    _backView2 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backview1.frame)+5, kSCREEN_WIDTH, 40)];
    _backView2.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_backView2];

    UIImageView *leftImage2 = [[UIImageView alloc]initWithFrame:CGRectMake(10, 7, 25, 25)];
    leftImage2.image = [UIImage imageNamed:@"f_icon04"];
    [_backView2 addSubview:leftImage2];
    UILabel *title2 = [[UILabel alloc]init];
    title2.text = @"故障设备:";
    title2.textColor = UIColorFromRGB(0x4d4d4d);
    title2.font = [UIFont systemFontOfSize:19.0];
    [_backView2 addSubview:title2];
    [title2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftImage2.mas_right).offset(10);
        make.top.equalTo(_backView2).offset(10);
        make.size.mas_equalTo(CGSizeMake(90, 21));
    }];
    _sbTF = [[UITextField alloc]init];
    _sbTF.enabled = NO;
    _sbTF.placeholder = @"选择故障设备";
    _sbTF.textColor = UIColorFromRGB(0x4d4d4d);
    _sbTF.backgroundColor = UIColorFromRGB(0xf0f0f0);
    _sbTF.font = [UIFont systemFontOfSize:15.0];
    [_backView2 addSubview:_sbTF];
    [_sbTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_backView2).offset(5);
        make.left.equalTo(title2.mas_right).offset(5);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH-145, 30));
    }];

    _sbBtn = [UIButton buttonWithType:UIButtonTypeSystem];

    _sbBtn.backgroundColor = [UIColor clearColor];

    [_sbBtn addTarget:self action:@selector(chooseClick:) forControlEvents:UIControlEventTouchUpInside];
    _sbBtn.tag = 1002;
    [_backView2 addSubview:_sbBtn];
    [_sbBtn mas_makeConstraints:^(MASConstraintMaker *make) {

        make.center.equalTo(_sbTF);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH-145, 30));
    }];
    
    //故障类型
    _backView3 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView2.frame)+5, kSCREEN_WIDTH, 40)];
    _backView3.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_backView3];

    UIImageView *leftImage4 = [[UIImageView alloc]initWithFrame:CGRectMake(10, 7, 25, 25)];
    leftImage4.image = [UIImage imageNamed:@"icon_type"];
    [_backView3 addSubview:leftImage4];
    UILabel *title4 = [[UILabel alloc]init];
    title4.text = @"故障类型:";
    title4.textColor = UIColorFromRGB(0x4d4d4d);
    title4.font = [UIFont systemFontOfSize:19.0];
    [_backView3 addSubview:title4];
    [title4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftImage4.mas_right).offset(10);
        make.top.equalTo(_backView3).offset(10);
        make.size.mas_equalTo(CGSizeMake(90, 21));
    }];



    _gztypeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_gztypeBtn setTitleColor:UIColorFromRGB(0xbfbfc4) forState:UIControlStateNormal];
    _gztypeBtn.backgroundColor = UIColorFromRGB(0xf0f0f0);
    _gztypeBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    _gztypeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_gztypeBtn addTarget:self action:@selector(ShowChooseView:) forControlEvents:UIControlEventTouchUpInside];
    isSelect = NO;
    [_backView3 addSubview:_gztypeBtn];

    [_gztypeBtn mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(_backView3).offset(5);
        make.left.equalTo(title4.mas_right).offset(5);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH-145, 30));
    }];


    //故障标题
    UIView *backview5 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView3.frame)+5, kSCREEN_WIDTH, 40)];
    backview5.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:backview5];

    UIImageView *leftImage6 = [[UIImageView alloc]initWithFrame:CGRectMake(10, 7, 25, 25)];
    leftImage6.image = [UIImage imageNamed:@"icon_title"];
    [backview5 addSubview:leftImage6];
    UILabel *title6 = [[UILabel alloc]init];
    title6.text = @"故障标题:";
    title6.textColor = UIColorFromRGB(0x4d4d4d);
    title6.font = [UIFont systemFontOfSize:19.0];
    [backview5 addSubview:title6];
    [title6 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftImage6.mas_right).offset(14);
        make.top.equalTo(backview5).offset(10);
        make.size.mas_equalTo(CGSizeMake(90, 21));
    }];
    _gzTitleTF = [[UITextField alloc]init];
    _gzTitleTF.clearButtonMode = UITextFieldViewModeAlways;
    _gzTitleTF.placeholder = @"输入故障标题";
    _gzTitleTF.borderStyle = UITextBorderStyleNone;
    _gzTitleTF.textColor = UIColorFromRGB(0x4d4d4d);
    [backview5 addSubview:_gzTitleTF];
    [_gzTitleTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backview5).offset(5);
        make.left.equalTo(title6.mas_right).offset(5);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH-145, 30));
    }];
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = [UIColor blackColor];
    [backview5 addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_gzTitleTF.mas_bottom).offset(1);
        make.left.equalTo(title6.mas_right).offset(5);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH-145, 1));
    }];
    //上传图片
    UIView *backview6 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(backview5.frame)+5, kSCREEN_WIDTH, 150)];
    backview6.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:backview6];

    UIImageView *leftImage7 = [[UIImageView alloc]initWithFrame:CGRectMake(10, 5, 33, 25)];
    leftImage7.image = [UIImage imageNamed:@"pic_icon"];
    [backview6 addSubview:leftImage7];
    UILabel *title7 = [[UILabel alloc]init];
    title7.text = @"图片上传";
    title7.textColor = UIColorFromRGB(0x4d4d4d);
    title7.font = [UIFont systemFontOfSize:19.0];
    [backview6 addSubview:title7];
    [title7 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftImage7.mas_right).offset(5);
        make.top.equalTo(backview6).offset(10);
        make.size.mas_equalTo(CGSizeMake(90, 21));
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(imageSize, imageSize);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, imageSize + 20) collectionViewLayout:layout];
    self.collectionView = collectionView;
    [backview6 addSubview:collectionView];
    
    [self.collectionView registerClass:[KKUploadPhotoCollectionViewCell class] forCellWithReuseIdentifier:collectionViewCellId];
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];

    //故障描述
    self.backview7 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(backview6.frame)+5, kSCREEN_WIDTH, 150)];
    self.backview7.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.backview7];

    UIImageView *leftImage8 = [[UIImageView alloc]initWithFrame:CGRectMake(10, 7, 25, 25)];
    leftImage8.image = [UIImage imageNamed:@"f_icon05"];
    [self.backview7 addSubview:leftImage8];
    UILabel *title8 = [[UILabel alloc]init];
    title8.text = @"故障描述";
    title8.textColor = UIColorFromRGB(0x4d4d4d);
    title8.font = [UIFont systemFontOfSize:19.0];
    [self.backview7 addSubview:title8];
    [title8 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftImage8.mas_right).offset(5);
        make.top.equalTo(self.backview7).offset(10);
        make.size.mas_equalTo(CGSizeMake(90, 21));
    }];
    _detailText = [[PHATextView alloc]init];
    _detailText.placeholder = @"不超过100个字符";
    _detailText.font = [UIFont systemFontOfSize:17.0];
    _detailText.delegate = self;
    _detailText.backgroundColor = [UIColor whiteColor];
    _detailText.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    _detailText.layer.borderWidth = 0.5;
    _detailText.layer.cornerRadius = 3;
    [self.backview7 addSubview:_detailText];
    [_detailText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(title8.mas_bottom).offset(10);
        make.left.equalTo(self.backview7).offset(15);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH-30, 100));
    }];
    //故障编辑
        if (self.stationId > 0 && self.faultTypeName.length > 1) {
     
        equipID = self.equipId;
        [_gztypeBtn setTitle:self.faultTypeName forState:UIControlStateNormal];
        [_gztypeBtn setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
        fttpid = self.faultTypeId;
        _gzTitleTF.text = self.GZtitle;
        _detailText.text = self.discrib;
        [self SBnetworking];

    }else{
        //正常上报
        [_gztypeBtn setTitle:@"选择故障类型" forState:UIControlStateNormal];
    }

    self.backView8 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backview7.frame)+5, kSCREEN_WIDTH, 40)];
    self.backView8.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.backView8];

    
        _chosupPsonLab = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 60, 21)];
        _chosupPsonLab.text = @"报送人";
        _chosupPsonLab.textColor = UIColorFromRGB(0x4d4d4d);
        _chosupPsonLab.font = [UIFont systemFontOfSize:19.0];
        [self.backView8 addSubview:_chosupPsonLab];
        _chosUpPsonBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _chosUpPsonBtn.frame = CGRectMake(85, 5, kSCREEN_WIDTH-90, 30);
        _chosUpPsonBtn.backgroundColor = UIColorFromRGB(0xf0f0f0);
        _chosUpPsonBtn.layer.cornerRadius = 5;
        [_chosUpPsonBtn setTitle:@"选择报送人名称" forState:UIControlStateNormal];
        [_chosUpPsonBtn setTitleColor:UIColorFromRGB(0xbfbfc4) forState:UIControlStateNormal];
        [_chosUpPsonBtn addTarget:self action:@selector(chosupPsonBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.backView8 addSubview:_chosUpPsonBtn];
    
    UIView *backView9 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backView8.frame)+5, kSCREEN_WIDTH, 60)];
    backView9.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:backView9];

    
    //提交取消bttuon
    _updata = [UIButton buttonWithType:UIButtonTypeSystem];
    [_updata setTitle:@"提交" forState:UIControlStateNormal];
    [_updata setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_updata addTarget:self action:@selector(up) forControlEvents:UIControlEventTouchUpInside];
    _updata.backgroundColor = UIColorFromRGB(0x2dd500);
    [backView9 addSubview:_updata];
    [_updata mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backView9).offset(10);
        make.left.equalTo(self.scrollView).offset((kSCREEN_WIDTH/3-20)/2);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
    }];
    
    UIButton *cancerl = [UIButton buttonWithType:UIButtonTypeSystem];
    [cancerl setTitle:@"取消" forState:UIControlStateNormal];
    [cancerl setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancerl addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    cancerl.backgroundColor = UIColorFromRGB(0xd50037);
    [backView9 addSubview:cancerl];
    [cancerl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backView9).offset(10);
        make.left.equalTo(_updata.mas_right).offset(20);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
    }];
    
    self.scrollView.contentSize = CGSizeMake(kSCREEN_WIDTH, CGRectGetMaxY(backView9.frame)+50);
}
- (void)ShowChooseView:(UIButton *)sender{
    
    if (isSelect) {
        //isSelect = NO;btn再次点击移除选择菜单
        isSelect = !isSelect;
        [_dataSource0 removeAllObjects];
        [_dataSource1 removeAllObjects];
        [_dataSource2 removeAllObjects];
        [_typeIDArr1 removeAllObjects];
        [_typeIDArr2 removeAllObjects];
        [_typeIDArr3 removeAllObjects];
        //_MenusView.alpha = 0;
        [_MenusView removeFromSuperview];
    }else{
        
        [self typeLoad];
        //_MenusView.alpha = 1;
        isSelect = YES;
    }
}
/*故障类型选择确定键*/
- (void)CancelChooseView:(UIButton *)sender{
    
    isSelect = !isSelect;
    [_dataSource0 removeAllObjects];
    [_dataSource1 removeAllObjects];
    [_dataSource2 removeAllObjects];
    [_typeIDArr1 removeAllObjects];
    [_typeIDArr2 removeAllObjects];
    [_typeIDArr3 removeAllObjects];
    //_MenusView.alpha = 0;
    [_MenusView removeFromSuperview];
    
}

//选择报送人按键事件
- (void)chosupPsonBtnClick:(UIButton *)sender{
    
    MHActionSheet *actionSheet = [[MHActionSheet alloc] initSheetWithTitle:nil style:MHSheetStyleDefault itemTitles:_UpPsonNameArr];
    __weak typeof(self) weakSelf = self;
    [actionSheet didFinishSelectIndex:^(NSInteger index, NSString *title) {
        [weakSelf.chosUpPsonBtn setTitle:title forState:UIControlStateNormal];
        [weakSelf.chosUpPsonBtn setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
        UpPsonId = [_UpPsonId[index]integerValue];
        //equipID = [_sbID[index]integerValue];
        
    }];
}
#pragma mark  UICollectionView数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.imageArray.count < 5) {
        return self.imageArray.count + 1;
    }
    return self.imageArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    KKUploadPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionViewCellId forIndexPath:indexPath];
    //添加子控件,设置布局与控件图片
    [self addAndSetSubViews:cell indexPath:indexPath];
    return cell;
}

- (void)addAndSetSubViews:(KKUploadPhotoCollectionViewCell *)cell indexPath:(NSIndexPath *)indexPath{
    //清空子控件,解决重用问题
    NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
    for (UIView *subview in subviews) {
        [subview removeFromSuperview];
    }
    UIImageView *imageView = [[UIImageView alloc]init];
    [cell.contentView addSubview:imageView];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.layer.masksToBounds = YES;
    cell.tag = 11; //根据tag值设定是否可点击,11可点击,初始全部可点击
    cell.imageView = imageView;
    cell.backgroundColor = [UIColor whiteColor];
    if(indexPath.row == self.imageArray.count){
        imageView.image = [UIImage imageNamed:@"add"];
    }else{
        imageView.image = nil;
    }
    
    UIButton *cancleBtn = [[UIButton alloc]init];
    cell.cancleBtn = cancleBtn;
    [cell.contentView addSubview: cancleBtn];
    [cancleBtn setImage:[UIImage imageNamed:@"circle_delete"] forState:UIControlStateNormal];
    cancleBtn.hidden = YES;//初始将删除按钮隐藏
    cell.cancleBtn.tag = indexPath.row;
    [cell.cancleBtn addTarget:self action:@selector(cancleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.imageView.frame = CGRectMake(0, 0, imageSize, imageSize);
    cell.cancleBtn.frame = CGRectMake(60, 0, 20, 20);
    
    if (self.imageArray.count > indexPath.row) {
        if ([self.imageArray[indexPath.row] isKindOfClass:[UIImage class]]) {
            cell.imageView.image = nil;
            cell.imageView.image = self.imageArray[indexPath.row];
            cell.cancleBtn.hidden = NO;
            cell.tag = 10; //初始设置tag为11,当为10时,表示已经添加图片
        }
    }

}

#pragma mark  collectionView代理方法,添加照片
//点击collectionView跳转到相册
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([collectionView cellForItemAtIndexPath:indexPath].tag == 11) {
        [[KKPhotoPickerManager shareInstace] showActionSheetInView:self.view fromController:self completionBlock:^(NSMutableArray *imageArray) {
            for (int i = 0; i<imageArray.count; i++) {
                if (self.imageArray.count < 5) {
                    UIImage *image = imageArray[i];
                    [self.imageArray addObject:image]; //上传图片保存到数组
                }
            }
            [self.collectionView reloadData];
        }];
    }
    
}

#pragma mark  删除图片
- (void)cancleBtnClick:(UIButton *)sender{
    if (sender.tag < self.imageArray.count) {
        [self.imageArray removeObjectAtIndex:sender.tag];
        sender.hidden = YES;
        [self.collectionView reloadData];
    }
}

- (void)typeLoad{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_GZtype parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

        TypeDataModel *model = [[TypeDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (SectionOneFaultModel *OneModel in model.FaultType) {
            
            [_dataSource0 addObject:OneModel];
            [_typeIDArr1 addObject:[NSString stringWithFormat:@"%ld",OneModel.ID]];
            //第二层数组模型 2层
            NSMutableArray *arr1 = [[NSMutableArray alloc]init];
            //第二层数组 ID 2层
            NSMutableArray *IDArr1 = [[NSMutableArray alloc]init];
            //第三层数组ID   3层
            NSMutableArray *IDArr3 = [[NSMutableArray alloc]init];
            //第三层数组模型  3层
            NSMutableArray *arr3 = [[NSMutableArray alloc]init];
            for (SectionTowFaultModel *TowModel in OneModel.faultTypes) {
                [arr1 addObject:TowModel];
                [IDArr1 addObject:[NSString stringWithFormat:@"%ld",TowModel.ID]];
                NSMutableArray *arr2 = [[NSMutableArray alloc]init];
                NSMutableArray *IDArr2 = [[NSMutableArray alloc]init];
                for (SectionThreeFaultModel *ThreeModel in TowModel.faultTypes) {
                    [arr2 addObject:ThreeModel];
                    [IDArr2 addObject:[NSString stringWithFormat:@"%ld",ThreeModel.ID]];
                }
                [IDArr3 addObject:IDArr2];
                [arr3 addObject:arr2];
            }
            [_typeIDArr2 addObject:IDArr1];
            [_dataSource1 addObject:arr1];
            [_typeIDArr3 addObject:IDArr3];
            [_dataSource2 addObject:arr3];
            
        }

            [self initView];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];

}

- (void)back{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您是否确定退出当前页面" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *OkAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:OkAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}
- (void)chooseClick:(UIButton *)sender
{

            MHActionSheet *actionSheet = [[MHActionSheet alloc] initSheetWithTitle:nil style:MHSheetStyleDefault itemTitles:_sbName];
            __weak typeof(self) weakSelf = self;
            [actionSheet didFinishSelectIndex:^(NSInteger index, NSString *title) {
                weakSelf.sbTF.text = title;
                equipID = [_sbID[index]integerValue];
                
            }];

}

//根据站点ID获取设备
- (void)SBnetworking{
    

    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:EquipURL parameters:@{@"stationId":[NSString stringWithFormat:@"%ld",self.stationId]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [_sbName removeAllObjects];
        [_sbID removeAllObjects];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        XJEqDataModel *dataModel = [[XJEqDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (XJEqListModel *model in dataModel.Equiplist){
            [_sbName addObject:model.equipName];
            [_sbID addObject:[NSString stringWithFormat:@"%ld",model.equipId]];
        }
        if (self.equipId > 0) {
            for (NSInteger i = 0; i<_sbID.count; i++) {
                if (self.equipId == [_sbID[i]integerValue]) {
                    _sbTF.text = _sbName[i];
                    equipID = [_sbID[i]integerValue];
                }else{
                    
                }
            }
        }else{
        
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)shangjiPsonLoad{
    
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:K_UpPsonURL parameters:@{@"userId":[NSString stringWithFormat:@"%ld",self.userId]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [_UpPsonId removeAllObjects];
        [_UpPsonNameArr removeAllObjects];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        YYUpPsonDataModel *datamodel = [[YYUpPsonDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (YYUpPsonBeanList *model in datamodel.beanList) {
            NSString *str = [NSString stringWithFormat:@"%@%c%@%c",model.userN,'(',model.postName,')'];
            [_UpPsonNameArr addObject:str];
            [_UpPsonId addObject:[NSString stringWithFormat:@"%ld",model.userId]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

// 上交故障
- (void)up{
    
    [UIView animateWithDuration:0 delay:1.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        _updata.userInteractionEnabled = NO;
    } completion:^(BOOL finished) {
        _updata.userInteractionEnabled = YES;
    }];
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    _dateString = [dateFormatter stringFromDate:currentDate];
    if (_gzTitleTF.text.length > 30) {
        
        [self showAlert:@"标题超过限定长度" message:nil actionWithTitle:@"确定"];
    }else if (_detailText.text.length > 100){
        
        [self showAlert:@"描述超过限定长度" message:nil actionWithTitle:@"确定"];
        
    }else if ((_stationTF.text.length < 1 || _sbTF.text.length < 1 || [_gztypeBtn.titleLabel.text isEqualToString:@"选择故障类型"] || _detailText.text.length < 1 || _gzTitleTF.text.length < 1 || [_chosUpPsonBtn.titleLabel.text isEqualToString:@"选择报送人名称"]) && switState == 1 ){
        
        [self showAlert:@"温馨提示" message:@"请完善提交信息" actionWithTitle:@"确定"];
    }
    else{

        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        self.manager.requestSerializer.timeoutInterval = 15;
        if (self.GZID == 0) {
            _paramete = @{equipid:[NSString stringWithFormat:@"%ld",equipID],findid:[NSString stringWithFormat:@"%ld",self.userId],updataTitle:_gzTitleTF.text,disc:_detailText.text,fttp:[NSString stringWithFormat:@"%ld",fttpid],updataTime:_dateString,@"isReport":[NSString stringWithFormat:@"%ld",switState],@"HeadPsonId":[NSString stringWithFormat:@"%ld",UpPsonId]};
        }else{
            //用户故障编辑时的参数
                _paramete = @{equipid:[NSString stringWithFormat:@"%ld",equipID],findid:[NSString stringWithFormat:@"%ld",self.userId],updataTitle:_gzTitleTF.text,disc:_detailText.text,fttp:[NSString stringWithFormat:@"%ld",fttpid],updataTime:self.ocTime,@"isReport":[NSString stringWithFormat:@"%ld",switState],@"faultId":[NSString stringWithFormat:@"%ld",self.GZID],@"HeadPsonId":[NSString stringWithFormat:@"%ld",UpPsonId]};
        }

        [_manager POST:K_GZupdata parameters:_paramete constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    
            for (int i = 0; i<self.imageArray.count; i++) {
        
            NSData *imageData =UIImageJPEGRepresentation(self.imageArray[i], 0.5);
                CGFloat dataBytes = imageData.length/1000.0;
                CGFloat maxQuality = 0.5f;
                CGFloat lastData = dataBytes;
                while (dataBytes > 300 && maxQuality > 0.1f) {
                    maxQuality = maxQuality - 0.1f;
                    imageData = UIImageJPEGRepresentation(self.imageArray[i], maxQuality);
                    dataBytes = imageData.length / 1000.0;
                    if (lastData == dataBytes) {
                        break;
                    }else{
                        lastData = dataBytes;
                    }  
                }

                NSString *fileName = [NSString  stringWithFormat:@"image%d.jpg", i];
                [formData appendPartWithFileData:imageData name:@"GZLR" fileName:fileName mimeType:@"image/jpeg"];
            
            }
        

        } progress:^(NSProgress * _Nonnull uploadProgress) {

        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSInteger status = [dic[@"status"]integerValue];
            NSSLog(@"%@",dic);
            if (status == 1) {
                //延时操作
                [UIView animateWithDuration:0 delay:2.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                
                    [[YXAlertHUD stateHUDWithHUDTyep:0 message:@"提交成功" textColor:[UIColor blackColor] iconColor:[UIColor greenColor]] show];
                
                } completion:^(BOOL finished) {
                
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            
            }else{
            
                [self showAlert:@"提交失败" message:dic[@"message"] actionWithTitle:@"我知道了"];
            }
            [MBProgressHUD hideHUDForView:self.view animated:YES];
    
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            NSInteger status = responses.statusCode;
            //        NSSLog(@"%ld",(long)responses.statusCode);
            if (status >=500) {
                [self showAlert:@"提交失败" message:@"服务器出错" actionWithTitle:@"我知道了"];
            }else{
                [self showAlert:@"提交失败" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
            }
        }];
    }
}

#pragma mark 封装提示框
-(void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
#pragma mark - WSDropMenuView DataSource -
- (NSInteger)dropMenuView:(ChooseMenus *)dropMenuView numberWithIndexPath:(WSIndexPath *)indexPath{
    
    //WSIndexPath 类里面有注释
    
    if (indexPath.row == WSNoFound) {
        
        return _dataSource0.count;
    }
    if (indexPath.row != WSNoFound && indexPath.item == WSNoFound) {
        NSArray *arr = _dataSource1[indexPath.row];
        return arr.count;
    }
    
    if (indexPath.row != WSNoFound && indexPath.item != WSNoFound && indexPath.rank == WSNoFound) {
        NSArray *arr = _dataSource2[indexPath.row][indexPath.item];
        return arr.count;
    }
    

    
    return 0;
}

- (NSString *)dropMenuView:(ChooseMenus *)dropMenuView titleWithIndexPath:(WSIndexPath *)indexPath{
    
    //return [NSString stringWithFormat:@"%ld",indexPath.row];
    
    //左边 第一级
    if (indexPath.row != WSNoFound && indexPath.item == WSNoFound) {
        SectionOneFaultModel *model = _dataSource0[indexPath.row];
        
        return model.name;
    }
    
    if (indexPath.row != WSNoFound && indexPath.item != WSNoFound && indexPath.rank == WSNoFound) {
        
        SectionTowFaultModel *model = _dataSource1[indexPath.row][indexPath.item];
        
        
        
        return model.name;
    }
    
    if (indexPath.row != WSNoFound && indexPath.item != WSNoFound && indexPath.rank != WSNoFound) {
        SectionThreeFaultModel *model = _dataSource2[indexPath.row][indexPath.item][indexPath.rank];
        
        return model.name;
    }
    
    
    return @"";
    
}
- (UIScrollView *)scrollView{
    if (!_scrollView) {
            _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _scrollView.backgroundColor = UIColorFromRGB(0xf0f0f0);
        
            // 隐藏水平滚动条
            _scrollView.showsHorizontalScrollIndicator = NO;
            _scrollView.showsVerticalScrollIndicator = NO;
    }
    return _scrollView;
}
@end
